package cn.edu.nyist.controller;


import cn.edu.nyist.entity.CommonUser;
import cn.edu.nyist.entity.Region;
import cn.edu.nyist.entity.RentHouse;
import cn.edu.nyist.entity.UserRentInfo;
import cn.edu.nyist.service.RegionService;
import cn.edu.nyist.service.RentHouseService;
import cn.edu.nyist.service.UserRentInfoService;
import cn.edu.nyist.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.jws.WebParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (RentHouse)表控制层
 *
 * @author cgq
 * @since 2021-03-21 17:54:46
 */
@Controller
@RequestMapping("rentHouse")
public class RentHouseController {

    @Value("${img.location.rentHouse}")
    private String folder;

    private static Logger log = LoggerFactory.getLogger(RentHouseController.class);

    @Autowired
    private AjaxResult ajaxResult;

    @Autowired
    private RentHouseService rentHouseService;

    @Autowired
    private UserRentInfoService userRentInfoService;

    @Autowired
    private RegionService regionService;


    @GetMapping("/house")
    public String house(HttpSession session){

        List<Region> regions = regionService.queryAllRegion();
        session.setAttribute(Const.REGIONLIST,regions);
        return "yju/rentHouse/rentHouseList";
    }

    @RequestMapping("/rentHouseList")
    @ResponseBody
    //房屋的标题，房屋类型，户型，地区，小区，租房类型，装修情况，朝向,楼层
    public Object rentHouseList(@RequestParam(value = "page", defaultValue = "1") Integer pageno,
                                @RequestParam(value = "limit", defaultValue = "5") Integer pagesize,
                                String title , String type , String houseType , String region,
                                String housingEstate , String rentType , String decoration,
                                String orientation, String floorLevel){



        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(title)) {
            log.info("title:"+title);
            paramMap.put("title",title);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(type)) {
            log.info("type:"+type);
            paramMap.put("type",type);
        }
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if(!StringUtils.isEmpty(housingEstate)) {
            log.info("housingEstate:"+housingEstate);
            paramMap.put("housingEstate",housingEstate);
        }
        if(!StringUtils.isEmpty(rentType)) {
            log.info("rentType:"+rentType);
            paramMap.put("rentType",rentType);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }

        if(!StringUtils.isEmpty(floorLevel)) {
            log.info("floorLevel:"+floorLevel);
            paramMap.put("floorLevel",floorLevel);
        }

        PageBean<RentHouse> pageBean = rentHouseService.queryPage(paramMap);
        Map<String,Object> rest = new HashMap();
        rest.put("code", 0);
        rest.put("msg", "");
        rest.put("count",pageBean.getTotalsize());
        rest.put("data", pageBean.getDatas());
        return rest;
    }

    //BelongUser

    @RequestMapping("/rentHouseListBelongUser")
    @ResponseBody
    public Object rentHouseListBelongUser(@RequestParam(value = "page", defaultValue = "1") Integer pageno,
                                @RequestParam(value = "limit", defaultValue = "5") Integer pagesize,
                                          HttpSession session){
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //从session中取出commonUser对象
        CommonUser commonUser = (CommonUser) session.getAttribute(Const.COMMONUSER);
        paramMap.put("userId",commonUser.getId());

        PageBean<RentHouse> pageBean = rentHouseService.queryPageBelongUser(paramMap);
        Map<String,Object> rest = new HashMap();
        rest.put("code", 0);
        rest.put("msg", "");
        rest.put("count",pageBean.getTotalsize());
        rest.put("data", pageBean.getDatas());
        return rest;
    }



    @RequestMapping("/rentHouseIndexList")
    @ResponseBody
    //地区 minPrice租金最小值 ， maxPrice租金最大值 ，厅室，租房类型，朝向、装修
    //房租说明 电梯 可做饭 南北通透
    //标题
    public Map<String,Object> rentHouseIndexList(@RequestParam(defaultValue = "1") Integer pageno,
                                     @RequestParam(defaultValue = "6") Integer pagesize,
                                     String region  , @RequestParam(defaultValue = "0") Double minPrice ,
                                     @RequestParam(defaultValue = "9999999") Double maxPrice, String houseType ,
                                     String rentType  , String orientation, String decoration,
                                     String priceExplain , Integer lift , Integer cook , Integer northSouth,
                                    String title){

        Map<String,Object> paramMap = new HashMap();
        paramMap.put("pageno",pageno);
        paramMap.put("pagesize",pagesize);

        //判断是否为空
        if(!StringUtils.isEmpty(region)) {
            log.info("region:"+region);
            paramMap.put("region",region);
        }
        if( minPrice != null ) {
            log.info("minPrice:"+minPrice);
            paramMap.put("minPrice",minPrice);
        }
        if( maxPrice != null ) {
            log.info("maxPrice:"+maxPrice);
            paramMap.put("maxPrice",maxPrice);
        }
        if(!StringUtils.isEmpty(houseType)) {
            log.info("houseType:"+houseType);
            paramMap.put("houseType",houseType);
        }
        if(!StringUtils.isEmpty(rentType)) {
            log.info("rentType:"+rentType);
            paramMap.put("rentType",rentType);
        }
        if(!StringUtils.isEmpty(orientation)) {
            log.info("orientation:"+orientation);
            paramMap.put("orientation",orientation);
        }
        if(!StringUtils.isEmpty(decoration)) {
            log.info("decoration:"+decoration);
            paramMap.put("decoration",decoration);
        }

        if(!StringUtils.isEmpty(priceExplain)) {
            log.info("priceExplain:"+priceExplain);
            paramMap.put("priceExplain",priceExplain);
        }
        if( lift != null ) {
            log.info("lift:"+lift);
            paramMap.put("lift",lift);
        }
        if(cook != null ) {
            log.info("cook:"+cook);
            paramMap.put("cook",cook);
        }
        if(northSouth !=null) {
            log.info("northSouth:" + northSouth);
            paramMap.put("northSouth", northSouth);
        }

        if(!StringUtils.isEmpty(title)) {
            log.info("title:" + title);
            paramMap.put("title", title);
        }
        PageBean<RentHouse> pageBean = rentHouseService.queryPage(paramMap);

        Map<String,Object> rest = new HashMap();
//        rest.put("code", 0);
//        rest.put("msg", "");
        //总条数
        rest.put("count",pageBean.getTotalsize());
        //当前页
        rest.put("pageno",pageBean.getPageno());
        //总页数
        rest.put("totalno",pageBean.getTotalno());
        rest.put("data", pageBean.getDatas());
        return rest;
    }


    /**
     * 跳转添加租房信息页面
     * @return
     */
    @GetMapping("/addRentHouse")
    public String addRentHouse(String type, Integer id, Model model,HttpSession session){

        if(type != null && type.equals("edit")){
            RentHouse  rentHouse = rentHouseService.selectById(id);
            model.addAttribute(Const.RENTHOUSE,rentHouse);
            model.addAttribute(Const.RENTHOUSEIMGS,rentHouse.getPicture());
        }
        return "yju/rentHouse/addRentHouse";
    }

    /**
    *查看详细信息
    */
    @GetMapping("detailRentHouse")
    public String detailRentHouse(Integer id, Model model){
            RentHouse  rentHouse = rentHouseService.selectById(id);
            model.addAttribute(Const.RENTHOUSE,rentHouse);
        return "yju/rentHouse/detailRentHouse";
    }

    /**
     * 添加地区  修改地区
     * @param rentHouse
     * @return
     */
    @PostMapping("/addRentHouse")
    @ResponseBody
    public AjaxResult submitAddRentHouse(RentHouse rentHouse,HttpSession session){

        if(rentHouse.getId() !=null){
            String rentHouseImgs =   (String) session.getAttribute(Const.RENTHOUSEIMGS);

            if ( rentHouseImgs !=null && StringUtils.isEmpty(rentHouse.getPicture())){
                rentHouse.setPicture(rentHouseImgs);
            }
            int count = rentHouseService.editByRentHouse(rentHouse);
            if(count > 0){
                ajaxResult.ajaxTrue("修改成功");
            }else{
                ajaxResult.ajaxFalse("修改失败");
            }
        }else{
            String rentHouseImgs =   (String) session.getAttribute(Const.RENTHOUSEIMGS);
            if (rentHouseImgs == null){
                ajaxResult.ajaxFalse("图片不能为空！");
            }else {
                rentHouse.setPicture(rentHouseImgs);
                String publishTime = DateUtil.getStringDate("yyyy-MM-dd");
                rentHouse.setPublishTime(publishTime);
                int count = rentHouseService.insertRentHouse(rentHouse);
                if (count > 0) {
                    //判断是否是普通用户添加
                    if(!StringUtils.isEmpty(session.getAttribute(Const.USERADDRENTHOUSE))
                            && "yes".equals(session.getAttribute(Const.USERADDRENTHOUSE))){
                        CommonUser user = (CommonUser) session.getAttribute(Const.COMMONUSER); 
                        // 创建userRentInfo 对象
                        UserRentInfo userRentInfo = new UserRentInfo(user.getId(),rentHouse.getId());
                        Integer rentCount = userRentInfoService.insert(userRentInfo);
                        if (rentCount >0){
                            ajaxResult.ajaxTrue("添加成功");
                        }else{
                            ajaxResult.ajaxFalse("添加失败");
                        }
                    }else {
                        ajaxResult.ajaxTrue("添加成功");
                        session.removeAttribute(Const.USERADDRENTHOUSE);
                    }
                } else {
                    ajaxResult.ajaxFalse("添加失败");
                }
            }
        }
        return ajaxResult;
    }

    /**
     * 根据id查询租房信息
     * @param id
     * @return
     */
    @RequestMapping("queryRentHouseById")
    @ResponseBody
    public RentHouse queryRentHouseById(Integer id){

        return  rentHouseService.selectById(id);

    }


    /**
     * 删除租房信息
     * @param data
     * @return
     */
    @PostMapping("/delRentHouse")
    @ResponseBody
    public AjaxResult delRentHouse(Data data,HttpSession session){
        for (Integer id : data.getIds()) {
            RentHouse rentHouse = rentHouseService.selectById(id);
            String picture = rentHouse.getPicture();
            deleteImg(picture);
        }
        if(!StringUtils.isEmpty(session.getAttribute(Const.USERRENTHOUSEINFOLIST))
                && "yes".equals(session.getAttribute(Const.USERRENTHOUSEINFOLIST))){
            CommonUser commonUser = (CommonUser) session.getAttribute(Const.COMMONUSER);
            List<Integer> ids = data.getIds();
            Map<String,Object> map = new HashMap<>();
            map.put("userId",commonUser.getId());
            map.put("ids",ids);
            //删除 user_rent_info
            int i = userRentInfoService.deleteByUserId(map);
            if( i >= 1 ){
                log.info("user_rent_info表中记录删除成功！");
            }
        }
        int count = rentHouseService.delByRentHouseIds(data.getIds());
        if(count >= data.getIds().size()){
            ajaxResult.ajaxTrue("删除成功");
            session.removeAttribute(Const.USERRENTHOUSEINFOLIST);
        }else{
            ajaxResult.ajaxFalse("删除失败");
        }
        return ajaxResult;
    }

    /**
     * 清除session中的 rentHouseImgs 属性
     *
     */
    @RequestMapping("/removeSeesionValue")
    @ResponseBody
    public AjaxResult removeSeesionValue(HttpSession session){
        String rentHouseImgs = (String) session.getAttribute(Const.RENTHOUSEIMGS);
        log.info("rentHouseImgs: "+rentHouseImgs);
        //删除图片
        deleteImg(rentHouseImgs);
        session.removeAttribute(Const.RENTHOUSEIMGS);
        rentHouseImgs = (String) session.getAttribute(Const.RENTHOUSEIMGS);
        if (StringUtils.isEmpty(rentHouseImgs)){
            ajaxResult.ajaxTrue("重置成功！");
        }else{
            ajaxResult.ajaxFalse("重置失败！");
        }
        return ajaxResult;

    }

    /**
    * 上传图片
    *
    */
    @PostMapping("/uploadImgs")
    @ResponseBody
    public AjaxResult uploadImgs(HttpServletRequest request, @RequestParam(value = "imgs", required = false) MultipartFile[] multipartImgs) throws IOException {
        log.info("上传图片");
        HttpSession session = request.getSession();
        StringBuffer rentHouseImgs =  new StringBuffer();
        try{

            for (int i=0;i<multipartImgs.length;i++) {
                MultipartFile img=multipartImgs[i];
                String fileName = img.getOriginalFilename();
                //文件名后缀
                String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
                String newFileName = System.currentTimeMillis() + "." + suffix;

                if(i==multipartImgs.length-1){
                    rentHouseImgs.append(newFileName);
                }
                else {
                    rentHouseImgs.append(newFileName+",");
                }
                log.info(folder+ newFileName);
                File localFile = new File(folder, newFileName);
                img.transferTo(localFile);
                log.info("http://localhost:8099"+"/upload/rentHouse/"+newFileName);
            }
            log.info(rentHouseImgs.toString());
            session.setAttribute(Const.RENTHOUSEIMGS,rentHouseImgs.toString());
            ajaxResult.ajaxTrue("图片上传成功！");

        }catch (Exception e){
            ajaxResult.ajaxFalse("图片上传失败！");
        }
        return ajaxResult;
    }

    /**
    *
    *删除图片
     */
    public void deleteImg(String rentHouseImgs){
        if (!StringUtils.isEmpty(rentHouseImgs)){
            String[] imgs = rentHouseImgs.split(",");
            for (String img : imgs) {
                String filePath = folder+img;
                log.info("filePath"+filePath);
                File file = new File(filePath);
                boolean delete = file.delete();
                log.info("图片删除情况："+delete);
            }
        }
    }

}